﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeiXinOpenMore
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            init();
        }

        public void init()
        {
            try
            {
                string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt");
                if (File.Exists(logPath))
                {
                    File.Delete(logPath);
                }
                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (DriveInfo drive in drives)
                {
                    if (drive.IsReady)
                    {
                        comboBox1.Items.Add(drive.Name.Remove(1));
                    }
                }

                string pageinfoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pageinfo.json");
                if (File.Exists(pageinfoPath))
                {
                    string content = File.ReadAllText(pageinfoPath);
                    if (!string.IsNullOrEmpty(content))
                    {
                        pageInfo pageinfo = JsonHelper.JsonToT<pageInfo>(content);
                        textBox1.Text = pageinfo.path; // 显示上次选择的路径
                        numericUpDown1.Value = pageinfo.num; // 显示上次选择的数量
                    }
                }
            }
            catch (Exception ex)
            {
                log("初始化失败，错误原因：" + ex.Message);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog of1 = new OpenFileDialog();
                of1.Title = "请选择应用的执行文件";
                of1.Multiselect = true;
                of1.Filter = "exe文件|*.exe";
                of1.Multiselect = false;
                if (of1.ShowDialog() == DialogResult.OK)
                {
                    textBox1.Text = string.Join(",", of1.FileNames);
                }
            }
            catch (Exception ex)
            {
                log("选择应用安装路径失败，错误原因：" + ex.Message);
                MessageBox.Show("选择应用安装路径失败，错误原因：" + ex.Message);
                return;
            }

        }

        private async void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBox2.Text))
            {
                MessageBox.Show("请输入应用的可执行文件名，例如：Weixin");
                return;
            }
            string[] appnames = textBox2.Text.Split(',');
            var pf = comboBox1.Text;
            // 检查是否选择了盘符
            if (string.IsNullOrEmpty(pf))
            {
                MessageBox.Show("请选择要搜索的盘符");
                return;
            }
            button2.Enabled = button1.Enabled = button3.Enabled = false;
            button2.Text = $"正在搜索";//  
            string txtpath = "";
            // 使用异步方法搜索文件
            await Task.Run(() => txtpath = seachFile(pf, appnames));

            button2.Enabled = button1.Enabled = button3.Enabled = true;
            button2.Text = $"自动搜索"; // 恢复按钮文本
            textBox1.Text = txtpath; // 显示搜索到的路径
            // 如果没有找到文件，提示用户
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("没有找到应用的安装路径，请手动选择");
                textBox1.Text = string.Empty; // 清空文本框 
                return;
            }

        }

        /// <summary>
        /// 搜索指定盘符下的应用安装路径
        /// </summary>
        /// <param name="pf"></param>
        /// <returns></returns>
        private string seachFile(string pf, string[] appNames)
        {
            try
            {
                string drive = $@"{pf}:\";  // 指定盘符（如D盘）

                foreach (string dir in Directory.EnumerateDirectories(drive))
                {
                    DirectoryInfo dirInfo = new DirectoryInfo(dir);
                    // 排除系统/隐藏目录
                    if ((dirInfo.Attributes & FileAttributes.System) == FileAttributes.System ||
                        (dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    {
                        continue;
                    }

                    foreach (string dir2 in Directory.EnumerateDirectories(dir))
                    {
                        try
                        {
                            DirectoryInfo dirInfo2 = new DirectoryInfo(dir2);
                            // 排除系统/隐藏目录
                            if ((dirInfo2.Attributes & FileAttributes.System) == FileAttributes.System ||
                                (dirInfo2.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                            {
                                continue;
                            }
                            foreach (var appName in appNames)
                            {
                                string[] allFiles = Directory.GetFiles(dir2, $"{appName}.exe", SearchOption.AllDirectories);
                                if (allFiles.Length > 0)
                                {
                                    return allFiles[0];
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            log("出错啦！具体错误：" + ex.Message);
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                log("搜索应用安装路径失败，错误原因：" + ex.Message);
                MessageBox.Show("搜索应用安装路径失败，错误原因：" + ex.Message);
                return "";
            }
            return "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string path = textBox1.Text.Trim();
                if (string.IsNullOrEmpty(path))
                {
                    MessageBox.Show("请搜索或输入应用安装路径");
                    return;
                }
                if (!File.Exists(path))
                {
                    MessageBox.Show("应用安装路径不正确，应用文件不存在");
                    return;
                }
                decimal num = numericUpDown1.Value;
                if (num < 1 || num > 10)
                {
                    MessageBox.Show("请设置正确的应用数量。最小1，最大10");
                    return;
                }
                // 检查是否已经运行
                string appname = Path.GetFileNameWithoutExtension(path);
                if (IsWeChatRunning(appname))
                {
                    log("应用已经在运行中，请先关闭应用。" + appname);
                    MessageBox.Show("应用已经在运行中，请先关闭应用。" + appname);
                    return;
                }
                // 生成bat文件
                string batContent = "";
                for (int i = 0; i < num; i++)
                {
                    batContent += $"start \"\" \"{path}\"\r\n";
                }
                string batPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "openapp.bat");
                string pageinfoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pageinfo.json");
                if (File.Exists(path))
                {
                    File.Delete(batPath); // 删除旧的bat文件
                }
                if (File.Exists(pageinfoPath))
                {
                    File.Delete(pageinfoPath); // 删除旧的记录文件
                }
                var pageinfoStr = JsonHelper.TtoJson(new pageInfo { path = path, num = (int)num });
                File.WriteAllText(batPath, batContent, Encoding.Default);
                File.WriteAllText(pageinfoPath, pageinfoStr, Encoding.UTF8);
                ProcessStartInfo startInfo = new ProcessStartInfo(batPath);
                startInfo.UseShellExecute = false;    // 禁用Shell执行以自定义配置
                startInfo.CreateNoWindow = true;      // 隐藏命令行窗口
                Process process = Process.Start(startInfo);
                process.WaitForExit();// 等待bat文件执行完成
                process.Close();
                if (File.Exists(path))
                {
                    File.Delete(batPath); // 删除旧的bat文件
                }
            }
            catch (Exception ex)
            {
                log("启动应用失败，错误原因：" + ex.Message);
                MessageBox.Show("启动应用失败，错误原因：" + ex.Message);
                return;
            }
        }

        public bool IsWeChatRunning(string appName)
        {
            Process[] processes = Process.GetProcessesByName(appName);
            return processes.Length > 0;

        }

        public void log(string msg)
        {
            string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt");
            using (StreamWriter sw = new StreamWriter(logPath, true))
            {
                sw.WriteLine($"{DateTime.Now}: {msg}");
            }
        }

        public class pageInfo
        {
            public string path { get; set; }
            public int num { get; set; }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            var comboBoxtext = comboBox2.Text;
            if (string.IsNullOrWhiteSpace(comboBoxtext))
            {
                textBox2.Text = "";
            }
            else if (comboBoxtext == "微信")
            {
                textBox2.Text = "Weixin,WeChat";
            }
            else if (comboBoxtext == "QQ")
            {
                textBox2.Text = "QQ";
            }
            else if (comboBoxtext == "企业微信")
            {
                textBox2.Text = "WXWork";
            }
        }

        
        private void button4_Click(object sender, EventArgs e)
        {
            MessageBox.Show("1.应用路径：应用的可执行文件路径，可以自行选择，例如：D:\\QQ.exe\r\n" +
               "2.安装盘符：在需要自动搜索时使用，应用安装在哪个盘下就选择哪个盘\r\n" +
               "3.应用名称：前面选择项是快捷选择，后面输入框是应用的可执行文件名称(不包含扩展名)，可以右键快捷方式的属性中查看，例如QQ.exe就输入QQ\r\n" +
               "4.应用数量：设置需要打开的应用数量，最小1，最大10\r\n" +
               "5.启动应用：打开选择的应用；应用路径为必填项，启动数量为必填项"
               , "使用方法");
        }
    }
}
